package cn.edu.ctbu.labtest.webapi;

import cn.edu.ctbu.labtest.core.PageUtils;
import cn.edu.ctbu.labtest.domain.Student;
import cn.edu.ctbu.labtest.service.StudentService;
import cn.edu.ctbu.labtest.utils.RUtil;
import cn.edu.ctbu.labtest.vo.R;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {

    @Autowired

    private StudentService studentService;
    /**
     * 读取的url：/webapi/student/list
     * @return
     */
    @GetMapping("/list")

    public List<Student> getAll(){
        List<Student> students=studentService.findAll();
        return students;
    }

    @GetMapping("/list1")
    public R<Page<Student>> list(int pageIndex, int pageSize){
        Pageable pageable=PageRequest.of(pageIndex,pageSize,Sort.by("id").descending());
        return RUtil.success(studentService.findAll(pageable));
    }

    /**
     * 分页读取分页
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0")Integer page,
                               @RequestParam(value = "size",defaultValue = "10")Integer size,
                               @RequestParam(value = "name",defaultValue = "")String name){
        //按id排倒序
        Sort sort=Sort.by(Sort.Direction.DESC,"id");
        Page<Student> studentPage;
        if (StringUtils.isEmpty(name)){
            Pageable pageable=PageRequest.of(page,size,sort);
            studentPage=studentService.findAll(pageable);
        }
        else {
            Student student=new Student();
            student.setName(name);
            Pageable pageable= PageRequest.of(0,3,sort);

            //全部模糊查询，即%（name）%
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student> example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }
        /*Pageable pageable=PageRequest.of(page,size,sort);

        Page<Student> studentPage=studentService.findAll(pageable);
        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());

        return pageUtils;*/
        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return  pageUtils;

    }


    /**
     * 读取的url：/webapi/student/get/id
     * @return
     */
    @GetMapping("/get/{id}")

    public Student get(@PathVariable Integer id){
        Student student=studentService.getById(id);
        student.setPassword("");
        return student;
    }

    /**
     * 新增学生方法/webapi/sudent/insert
     * @param student
     * @return*/
    @PostMapping("/insert")
    public Student insert(Student student){
        Student student1=studentService.insert(student);

        return student1;

    }

    /**
     * 修改学生方法、webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public Student update(Student student){
        Student oldstudent=studentService.getById(student.getId());
        if(StringUtils.isEmpty(student.getPassword())){
            //没有新密码就用旧密码
            student.setPassword(oldstudent.getPassword());
        }
        student=studentService.update(student);

        return student;

    }

    /**
     * 删除学生方法、webapi/student/delete
     * @param
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable  Integer id){

        studentService.delete(id);
    }

    /**
     * 按名字查询
     * @param name
     * @return
     */
    @RequestMapping("/find")
    public List<Student> findName(String name){
        List<Student> students=studentService.findByName(name);
        return students;
    }

    /**
     * 后端过滤检验
     * @param student
     * @param bindingResult
     * @return
     */
    @PostMapping(value = "/webapi/student/add")
    public int add(@Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){

            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;
        }
        studentService.add(student);
        Integer myid=student.getId();
        return myid.intValue();
    }

    @PostMapping("/add1")
    public R add1(@Valid Student student,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            String erroMsg=bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生出错了!{}",erroMsg);
            return RUtil.error(-10,erroMsg);
        }
        studentService.insert(student);
        return RUtil.success();
    }

    @GetMapping("/validateUser")
    public R validateNoAndPassword(String no,String password) throws Exception {
        return RUtil.success(studentService.validateUsernameAndPassword(no,password));
    }
}
